package org.rulix.ogame.player.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.rulix.ogame.player.api.OgamePlanet;
import org.rulix.ogame.player.api.OgamePlanetCoordinates;

public class OgameResponseHelper {
	
	private Source createSource(InputStream is) throws OgameException {
		Source source = null;
		
		try {
			source = new Source(is);
		} catch (IOException e) {
			throw new OgameException("Cannot read response to be parsed", e);
		}
		return source;
	}
	
	public boolean isLoggedIn(HttpResponse httpResponse, OgameSession ogameSession){
		Header locationHeader = httpResponse.getFirstHeader("Location");
		if ( locationHeader == null ){
			return false;
		}
		else if ( locationHeader.getValue().contains("loginError") ){
			return false;
		}
		else if ( locationHeader.getValue().contains("/game/index.php?page=overview&PHPSESSID")){
			return true;
		}
		else{
			return false;
		}
	}
	
	public List<OgamePlanet> getPlanets(InputStream is) throws OgameException {
		Source source = createSource(is);
		List<Element> smallplanets = source.getAllElementsByClass("smallplanet");
		List<OgamePlanet> ogamePlanets = Collections.synchronizedList(new ArrayList<OgamePlanet>());
		for (Element element : smallplanets) {
			Element first = element.getFirstElement(HTMLElementName.A);
			String valueHrefPlanet = first.getAttributeValue("href");

			first = element.getFirstElementByClass("planet-koords");
			String koords = first.getContent().toString();
			
			first = element.getFirstElementByClass("planet-name");
			String planetName = first.getContent().toString();
			
			OgamePlanet planet = new OgamePlanet();
			OgamePlanetCoordinates coords = OgamePlanetCoordinates.getCoordinates(koords);
			planet.setName(planetName);
			planet.setCoordinates(coords);
			
			List<NameValuePair> values = null;
			try {
				values = URLEncodedUtils.parse(new URI(valueHrefPlanet), null);
			} catch (URISyntaxException e) {
				throw new OgameException("Wrong planet uri '"+valueHrefPlanet+"'", e);
			}
			for (NameValuePair nameValuePair : values) {
				if(nameValuePair.getName().equals("cp"))
					planet.setCode(nameValuePair.getValue());
			}
			ogamePlanets.add(planet);
		}
		return ogamePlanets;
	}
	
	
	public int[] getResourcesForPlanet(OgameSession ogameSession, OgamePlanet ogamePlanet){
		return null;
	}

}
